/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ts, rule } from "qvog-dsl";

const SEVERITY = 2;
const DOC_PATH = 'docs/no-unsafe-innerhtml.md';
const DESCRIPTION = 'Assigning unvalidated data to innerHTML can lead to XSS vulnerabilities. Use a sanitization function before assignment.';

export default rule()
  .match(ts.isBinaryExpression)
  .when(node => {
      // 检查赋值表达式左侧是 .innerHTML
      if (node.operatorToken.kind !== ts.SyntaxKind.EqualsToken) return false;
      if (!ts.isPropertyAccessExpression(node.left)) return false;
      if (node.left.name.getText() !== 'innerHTML') return false;

      // 右侧是变量或表达式，但不是调用 sanitize()
      if (ts.isCallExpression(node.right)) {
          const expr = node.right.expression;
          if (ts.isIdentifier(expr) && expr.getText() === 'sanitize') {
              return false; // 已经经过 sanitize
          }
      }

      return true;
  })
  .report({
      severity: SEVERITY,
      description: DESCRIPTION,
      docPath: DOC_PATH,
  });
